package com.captain.leetcode;

/**
 * @author captain
 * @Des示例 1：
 * <p>
 * 输入：x = 2.00000, n = 10
 * 输出：1024.00000
 * 示例 2：
 * <p>
 * 输入：x = 2.10000, n = 3
 * 输出：9.26100
 * 示例 3：
 * <p>
 * 输入：x = 2.00000, n = -2
 * 输出：0.25000
 * 解释：2-2 = 1/22 = 1/4 = 0.25
 * @Date 2021/7/24 16:36
 */
public class PowXY50 {
    public static void main(String[] args) {
        System.out.println(new PowXY50().myPow(2, 4));
    }
    public double powRecursion(double x, int n) {
        //递归调用,退出条件 n越来越小   2 ^ 4   2^2 * 2^2 *2
        // 8/2 =4/2 = 1/2 = 0
        if (n == 0) {
            return 1;
        }
        //判断n为偶数还是奇数
        if (n % 2 == 0) {
            double powRecursion = powRecursion(x, n / 2);
            return powRecursion * powRecursion;
        } else {
            double powRecursion = powRecursion(x, n / 2);
            return powRecursion * powRecursion * x;
        }
    }

    public double myPow(double x, int n) {
        //x = 1时
        if (x == 1) return 1;
        //x = -1时
        if (x == -1) {
            if (n % 2 == 0) {
                return 1;
            } else {
                return -1;
            }
        }
        //x = -2 ^ 32 时
        if (n == -2147483648) return 0;
        double res;
        //判断n是否大于0 -n问题
        if (n > 0) {
            res = powRecursion(x, n);
        } else {
            n = -n;
            res = 1 / powRecursion(x, n);
        }
        return res;
    }
}
